package com.ihrm.system.interceptor;

import com.ihrm.common.entity.Constants;
import com.ihrm.common.exception.CommonException;
import com.ihrm.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class LoginInterceptor implements HandlerInterceptor {

    // 校验jwt
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        String authorization = request.getHeader("Authorization");

        if (StringUtils.isEmpty(authorization)) {
            throw new CommonException(Constants.UNAUTHENTICATED_CODE, Constants.UNAUTHENTICATED_MSG);
        }
        String token = authorization.replace("Bearer ", "");
        //比较并获取claims
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
            if (claims == null) {
                throw new CommonException(Constants.UNAUTHENTICATED_CODE, Constants.UNAUTHENTICATED_MSG);
            }
        }catch (Exception e) {
            throw new CommonException(Constants.UNAUTHENTICATED_CODE, Constants.UNAUTHENTICATED_MSG);
        }
        String userId = (String) claims.get("userId");
        request.setAttribute("userId", userId);
        return true;
    }
}